<template>
  <div class="execution">
    <basic-container>
<!--      :permission="permissionList"-->
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"

        :table-loading="tableLoading"
        :option="tableOption"
        v-model="form"
        @on-load="getList"
        :before-open="handleOpenBefore"
        :before-close="handleCloseBefore"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel">
        <template slot="msgContentForm" slot-scope="scope">
          <avue-ueditor v-model="scope.row.msgContent" :options="options" :disabled="dialogType==='view'"></avue-ueditor>
        </template>
        <template slot="receiveForm" slot-scope="scope">
          <div class="check-user-box">
            <el-row class="box-row line-row">
              <el-col class="col-sort"><span>部门</span> <el-button @click.stop="checkDep()" type="text" :disabled="dialogType==='view'" size="mini">选择</el-button></el-col>
              <el-col class="border-col">
                <div class="col-result" v-if="scope.row.sysMsgDepts && scope.row.sysMsgDepts.length">
                  <el-tag class="receive-tag" v-for="(item,i) in scope.row.sysMsgDepts" :key="'dep'+i" size="mini">{{item.deptName}}</el-tag>
<!--                  <span v-for="(item,index) in scope.row.sysMsgDepts">{{item.deptName}}{{scope.row.sysMsgDepts.length > index+1 ? '、': ''}}</span>-->
                </div>
                <div v-else class="col-result result-empty">没有选择部门{{depStr}}</div>
              </el-col>
            </el-row>

            <el-row class="box-row line-row">
              <el-col class="col-sort"><span>角色</span> <el-button  @click.stop="checkRole()" type="text" :disabled="dialogType==='view'" size="mini">选择</el-button></el-col>
              <el-col class="border-col">
                <div class="col-result" v-if="scope.row.sysMsgRoles && scope.row.sysMsgRoles.length">
                  <el-tag class="receive-tag" v-for="(item,i) in scope.row.sysMsgRoles" :key="'role'+i" size="mini">{{item.roleName}}</el-tag>
                </div>
                <div v-else class="col-result result-empty">没有选择角色{{roleStr}}</div>
              </el-col>
            </el-row>

            <el-row class="box-row">
              <el-col class="col-sort"><span>用户</span> <el-button  @click.stop="checkUser()" type="text" :disabled="dialogType==='view'" size="mini">选择</el-button></el-col>
              <el-col class="border-col">
                <div class="col-result" v-if="scope.row.sysMsgRecievers && scope.row.sysMsgRecievers.length">
                  <el-tag class="receive-tag" v-for="(item,i) in scope.row.sysMsgRecievers" :key="'user'+i" size="mini">{{item.receiverUserName}}</el-tag>
                </div>
                <div v-else class="col-result result-empty">没有选择用户{{userStr}}</div>
              </el-col>
            </el-row>
          </div>
        </template>

        <template slot="sendTypeForm" slot-scope="scope">
          <div class="timeform">
            <avue-radio v-model="scope.row.sendType" border :dic="timeType"></avue-radio>
            <div class="cron" v-if="scope.row.sendType == 2">
              <el-popover v-model="cronPopover">
                <cron i18n="cn" @change="changeCron" @close="cronPopover=false"/>
                <el-input
                  slot="reference"
                  v-model="scope.row.sendRule"
                  placeholder="请输入定时发送时间"
                  @click="cronPopover=true"/>
              </el-popover>
            </div>
          </div>

        </template>

        <template slot-scope="scope" slot="menu">
<!--          v-if="permissions.msg_edit"-->
          <el-button v-if="scope.row.msgStatus != '1'" type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row,scope.index)">编辑</el-button>
          <el-button v-if="scope.row.msgStatus != '1'" type="text" size="small" icon="el-icon-delete" @click="rowDel(scope.row,scope.index)">删除</el-button>
          <el-button v-if="scope.row.msgStatus != '1'" type="text" size="small" icon="el-icon-position" @click="handleSend(scope.row,scope.index)">发送</el-button>
          <el-button v-if="scope.row.msgStatus == '1'" type="text" size="small" icon="el-icon-aim" @click="sendResult(scope.row,scope.index)">发送结果</el-button>
        </template>

      </avue-crud>

    </basic-container>


    <check-user :show.sync="userVisible" :checkList="form.sysMsgRecievers" :msgId="form.msgId" @save="saveUser"></check-user>

    <check-role :show.sync="roleVisible" :checkList="form.sysMsgRoles" :msgId="form.msgId" @save="saveRole"></check-role>

    <check-dep :show.sync="depVisible" :checkList="form.sysMsgDepts" :msgId="form.msgId" @save="saveDep"></check-dep>

  </div>
</template>

<script>
  import Vue from 'vue'
  import AvueUeditor from 'avue-plugin-ueditor'
  Vue.use(AvueUeditor)
  import {addObj, delObj, fetchList, putObj,sendObj} from '@/api/message/message'
  import {tableOption,tableUserItemOption} from '@/const/crud/message/message'
  import {getStore} from '@/util/store'
  import {mapGetters} from 'vuex'
  import {cron} from 'vue-cron'
  import { remote } from '@/api/admin/dict'

  import checkUser from './user'
  import checkRole from './role'
  import checkDep from './dep'

  let that;
  export default {
    name: 'message',
    components: {cron,checkUser,checkRole,checkDep},
    data() {
      return {
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,

        timeType:[],
        cronPopover: false,
        text:'',
        options: {
          //普通图片上传
          action: "/admin/sys-file/upload",
          headers:{
            'Accept': 'application/json, text/plain, */*',
            'TENANT-ID': getStore({name: 'tenantId'}),
            'Authorization': 'Bearer ' + this.$store.getters.access_token,
          },
          customConfig: {},//wangEditor编辑的配置
          props: {
            res: "data",
            url: "url"
          },
        },

        dialogType: '',
        form:{
          sendRule: '',
          sysMsgRecievers: [],
          sysMsgRoles: [],
          sysMsgDepts: [],
          sendChannels: [],
          receiveRange: '1',
        },
        userStr: '',
        roleStr: '',
        depStr: '',

        rangeType:[
          {label: '部分',value: '1'},
          {label: '全部',value: '2'}
        ],

        userVisible: false,
        roleVisible: false,
        depVisible: false,

        msgChannelList: [],

      }
    },
    watch: {
      'form.time'(val){
        if (val == 1){
          delete this.form.sendRule
        }
      },

    },
    filters: {
      dictChannel(val){
        let list = that.msgChannelList;
        let item = list && list.find((item) => item.value == val);
        return item && item.label
      }
    },
    beforeCreate: function () {
      that = this;
    },
    created() {
      this.getTimeDict()
      remote('msg_channel').then(res => {
        this.msgChannelList = res.data.data
      })
    },
    mounted: function () {
    },
    computed: {
      ...mapGetters(['permissions']),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions.msg_add, false),
          delBtn: this.vaildData(this.permissions.msg_del, false),
          editBtn: this.vaildData(this.permissions.msg_edit, false)
        }
      }
    },
    methods: {
      //获取消息发送方式数据字典
      getTimeDict() {
        remote('msg_time_type').then(response => {
          const code = response.data.code
          if (code === 0) {
            this.timeType = response.data.data
          }
        })
      },
      getList(page, params) {
        this.tableLoading = true
        fetchList(Object.assign({
          descs: 'create_time',
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
        }).catch(err => {
          this.tableLoading = false
        })
      },
      changeCron(val) {
        this.form.sendRule = val
      },
      handleOpenBefore(show, type){
        this.dialogType = type
        if (!this.form.receiveRange || this.form.receiveRange === '1') {
          tableOption.column[5].addDisplay = true
          tableOption.column[5].editDisplay = true
          tableOption.column[5].viewDisplay = true
        } else if (this.form.receiveRange && this.form.receiveRange === '2') {
          tableOption.column[5].addDisplay = false
          tableOption.column[5].editDisplay = false
          tableOption.column[5].viewDisplay = false
        }
        show()
      },
      handleCloseBefore(done, type){
        this.userStr = ''
        this.roleStr = ''
        this.depStr = ''
        done()
      },
      handleEdit(row, index) {
        this.$refs.crud.rowEdit(row, index)
      },
      //点击列表的发送
      handleSend(row, index){
        this.$confirm('是否确发送该条信息？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return sendObj(row.msgId)
        }).then(data => {
          this.$message.success('发送成功')
          this.getList(this.page)
        })
      },
      rowDel: function (row, index) {
        this.$confirm('是否确认删除该条信息？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.msgId)
        }).then(data => {
          this.$message.success('删除成功')
          this.getList(this.page)
        })
      },
      //点击发送结果
      sendResult(row,index){
        this.$router.push(`/msgResult/index?msgId=${row.msgId}&msgTitle=${row.msgTitle}`)
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate: function (row, index, done, loading) {
        if (row.receiveRange == '1' && !row.sysMsgRecievers.length && !row.sysMsgRoles.length && !row.sysMsgDepts.length){
          this.$message.error('请至少选择一个接收对象')
          loading()
          return false
        }
        if (row.time == 2 && !row.sendRule){
          this.$message.error('请输入定时发送时间')
          loading()
          return false
        }
        putObj(row).then(data => {
          this.$message.success('修改成功')
          done()
          this.getList(this.page)
        }).catch(() => {
          loading()
        })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave: function (row, done, loading) {
        if (row.receiveRange == '1' && !row.sysMsgRecievers.length && !row.sysMsgRoles.length && !row.sysMsgDepts.length){
          this.$message.error('请至少选择一个接收对象')
          loading()
          return false
        }
        if (row.time == 2 && !row.sendRule){
          this.$message.error('请输入定时发送时间')
          loading()
          return false
        }
        addObj(row).then(data => {
          this.$message.success('添加成功')
          done()
          this.getList(this.page)
        }).catch(() => {
          loading()
        })
      },
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      searchReset() {
        this.searchForm = {}
        this.page.currentPage = 1
        this.getList(this.page)
      },
      refreshChange() {
        this.getList(this.page)
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      currentChange(current) {
        this.page.currentPage = current
      },

      checkUser(){
        this.userVisible = true
      },
      saveUser(list,str){
        this.form.sysMsgRecievers = list
        this.userStr = str
      },

      checkRole(){
        this.roleVisible = true
      },
      saveRole(list,str){
        this.form.sysMsgRoles = list
        this.roleStr = str
      },
      checkDep(){
        this.depVisible = true
      },
      saveDep(list,str){
        this.form.sysMsgDepts = list
        this.depStr = str
      },
      //保留多个空格
      keepSpace(detail){
        let matchResult = null;
        // 空格在正则中可以使用\u0020表示
        while(matchResult = detail.match(/\u0020{2,}/)){
          let replaceString = '';
          for(let i=0; i<matchResult[0].length; i++){
            replaceString += '&nbsp;';
          }
          detail = detail.replace(matchResult[0],replaceString);
        }
        return detail;

      },
    }
  }
</script>
<style lang="scss" scoped>
  .timeform{
    display: flex;
  }
  .cron{
    width: 60%;
  }
  .left-page{
    text-align: right;
    margin-top: 10px;
  }

  .receive-tag{
    margin-right: 5px;
  }

  .check-user-box{
    border: 1px solid #ddd;
    border-radius: 4px;


    .border-col{
      width: calc(100% - 100px);
      border-left: 1px solid #ddd;
    }

    .col-sort{
      width: 100px;
      text-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
      span{
        margin-right: 5px;
      }
    }

    .col-result{
      font-size: 14px;
      padding: 0 5px;
    }
    .result-empty{
      color: #F56C6C;
    }
    .el-col{
      margin-bottom: 0;
    }

    .line-row{
      border-bottom: 1px solid #ddd;
    }

  }
</style>
<style lang="scss">
  .collapse-col{
    border-top:none;
    .el-collapse-item__wrap,.el-collapse-item__header{
      border:none;
    }
  }
</style>
